<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="灌排管理"></page-header>

        <!-- 使用FilterTabs组件显示切换标签 -->
        <view class="tab-selection">
            <view
                class="tab-item"
                :class="{ active: activeTab === 'irrigation' }"
                @click="switchToIrrigation">
                智能灌溉
            </view>
            <view
                class="tab-item"
                :class="{ active: activeTab === 'drainage' }"
                @click="switchToDrainage">
                智能排水
            </view>
        </view>

        <!-- 灌排记录列表 -->
        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in records"
                :key="index"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editRecord(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view style="display: flex; align-items: center">
                            <image
                                style="margin-right: 10rpx"
                                class="icon-wrapper"
                                src="/static/images/guangai.png"
                                mode="aspectFill"></image>
                            <text class="date-text">
                                {{ activeTab === 'irrigation' ? '灌溉' : '排水' }}
                            </text>
                        </view>

                        <text class="date-small">
                            {{ formatDate(item.startDate) }} 至 {{ formatDate(item.endDate) }}
                        </text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <view class="info-row">
                            <text class="info-label">
                                {{ activeTab === 'irrigation' ? '灌溉地块' : '排水地块' }}
                            </text>
                            <text class="info-value">
                                {{ item.plotName }}-{{ item.fieldName || '' }}
                            </text>
                        </view>

                        <view class="info-row">
                            <text class="info-label">操作面积</text>
                            <text class="info-value">{{ item.area || 0 }} 亩</text>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>

                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="records.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>

        <!-- 无数据时显示空状态 -->
        <empty-data v-if="records.length === 0 && !loading" />

        <view
            class="add-button"
            @click="
                navigateTo(
                    '/pages/agriculture/irrigationManagement/addIrrigation?type=' + activeTab
                )
            ">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { irrigation } from '@/utils/api/index.js'
// 导入格式化函数
import { formatDateChinese, formatImages, formatToISOString } from '@/utils/util.js'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            activeTab: 'irrigation',
            records: [],
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            pageParams: {
                pageNo: 1,
                pageSize: 30,
                operationType: '1', // 默认灌溉类型
            },
        }
    },
    onShow() {
        this.fetchRecords()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchRecords()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        async fetchRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                // 设置operationType参数
                this.pageParams.operationType = this.activeTab === 'irrigation' ? '1' : '2'

                const res = await irrigation.getIrrigationDrainagePage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.records = [...this.records, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.records = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                } else {
                    // 如果API请求失败，使用默认数据
                    if (!isLoadMore) {
                        this.records = this.getDefaultData()
                    }
                }
            } catch (error) {
                console.error('获取灌排记录失败:', error)
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none',
                })
                // 使用默认数据
                if (!isLoadMore) {
                    this.records = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            if (this.activeTab === 'irrigation') {
                return [
                    {
                        id: 1,
                        operationType: '1',
                        startDate: '2023-07-23',
                        endDate: '2023-07-23',
                        plotId: '1',
                        fieldId: '2',
                        plotName: '一号地块',
                        fieldName: '2号条田',
                        area: 5.2,
                        images: '/static/images/rice1.jpg,/static/images/rice2.jpg',
                    },
                    {
                        id: 2,
                        operationType: '1',
                        startDate: '2023-07-20',
                        endDate: '2023-07-20',
                        plotId: '1',
                        fieldId: '2',
                        plotName: '一号地块',
                        fieldName: '2号条田',
                        area: 3.5,
                        images: '/static/images/rice1.jpg,/static/images/rice2.jpg',
                    },
                ]
            } else {
                return [
                    {
                        id: 1,
                        operationType: '2',
                        startDate: '2023-07-20',
                        endDate: '2023-07-20',
                        plotId: '2',
                        fieldId: '3',
                        plotName: '二号地块',
                        fieldName: '3号条田',
                        area: 4.7,
                        images: '/static/images/rice3.jpg',
                    },
                ]
            }
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.fetchRecords(true)
        },

        navigateTo(url) {
            uni.navigateTo({
                url,
            })
        },

        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        viewDetail(item) {
            // 跳转到详情页面
            uni.navigateTo({
                url: `/pages/agriculture/irrigationManagement/addIrrigation?id=${item.id}&type=${this.activeTab}`,
            })
        },

        editRecord(item) {
            // 编辑记录，跳转到编辑页面
            uni.navigateTo({
                url: `/pages/agriculture/irrigationManagement/addIrrigation?id=${item.id}&type=${this.activeTab}`,
            })
        },

        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条${
                    this.activeTab === 'irrigation' ? '灌溉' : '排水'
                }记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteRecord(item.id)
                    }
                },
            })
        },

        async deleteRecord(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await irrigation.deleteIrrigationDrainage(id)

                if (res.code === 0 && res.data) {
                    // 删除成功，更新列表
                    const index = this.records.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.records.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除灌排记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 切换到灌溉标签
        switchToIrrigation() {
            this.activeTab = 'irrigation'
            this.pageParams.pageNo = 1
            this.hasMore = true
            this.fetchRecords()
        },

        // 切换到排水标签
        switchToDrainage() {
            this.activeTab = 'drainage'
            this.pageParams.pageNo = 1
            this.hasMore = true
            this.fetchRecords()
        },
    },
}
</script>

<style lang="scss">
.tab-selection {
    display: flex;
    background-color: #fff;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;

    .tab-item {
        flex: 1;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 0 10rpx;

        &.active {
            background-color: #2e6140;
            color: #fff;
        }

        &:first-child {
            margin-left: 0;
        }

        &:last-child {
            margin-right: 0;
        }
    }
}
</style>
